package org.testmyapp.tasks;

import java.util.List;
import java.util.Map;

import org.testmyapp.engine.IEngineServices;
import org.testmyapp.entities.Bill;
import org.testmyapp.entities.BillPosition;
import org.testmyapp.persistence.BusinessObjectPersistenceProvider;

public class CheckCorrecture implements TaskWorker {

	public String validate(IEngineServices aes,
			Map<String, String[]> parameterMap, String processInstanceId,
			BusinessObjectPersistenceProvider bopp) {

		String korrekturType = (String) aes.getVariable("korrekturType",
				processInstanceId);
		String validation = parameterMap.get("validateCorrection")[0];
		Object korrekturObj = aes.getVariable("correctedObject",
				processInstanceId);
		Object objForKorrektur = aes.getVariable("objectToCorrect",
				processInstanceId);

		if (korrekturType == null || validation == null || korrekturObj == null
				|| objForKorrektur == null) {
			throw new RuntimeException(
					"Technical error: missing decisive variables");
		}

		if (validation.equals("true")) {
			if (korrekturType.equals("bill")) {
				try {
					Bill billNew = (Bill) korrekturObj;
					Bill billOld = (Bill) objForKorrektur;
					@SuppressWarnings("unchecked")
					List<Bill> bills = (List<Bill>) aes.getVariable("bills",
							processInstanceId);
					int indexOf = bills.indexOf(billOld);
					bills.set(indexOf, billNew);
				} catch (Exception e) {
					throw new RuntimeException(
							"Technical error: unable to get Bill", e);
				}
			} else if (korrekturType.equals("billPosition")) {
				try {
					BillPosition billPositionNew = (BillPosition) korrekturObj;
					BillPosition billPositionOld = (BillPosition) objForKorrektur;
					@SuppressWarnings("unchecked")
					List<BillPosition> BillPositions = (List<BillPosition>) aes
							.getVariable("billPositions", processInstanceId);
					int indexOf = BillPositions.indexOf(billPositionOld);
					BillPositions.set(indexOf, billPositionNew);
				} catch (Exception e) {
					throw new RuntimeException(
							"Technical error: unable to get BillPosition", e);
				}
			}
		}
		aes.setVariable(processInstanceId, "korrekturValid", validation);
		//reset it!
		aes.setVariable(processInstanceId, "korrekturType", null);
		aes.setVariable(processInstanceId, "objectToCorrect", null);
		aes.setVariable(processInstanceId, "correctedObject", null);
		return "";
	}
}
